package service

import (
	"go-base-learning/src/16_project02_customer/customerManager/model"
)

// CustomerService 完成对Customer的操作
type CustomerService struct {
	// customers 客户的切片
	customers []model.Customer
	// customerNum 当前客户数
	customerNum int
}

// NewCustomerService 提供一个CustomerService对象
func NewCustomerService() *CustomerService {
	return &CustomerService{
		customers:   make([]model.Customer, 0, 5),
		customerNum: 0,
	}
}

func (cs *CustomerService) Add(name string, gender string, age int, tel string, email string) (bool, string) {
	if gender != "男" && gender != "女" {
		return false, "请填写正确的性别"
	}
	if age < 18 {
		return false, "本店不接待未成年人哦～"
	} else if age > 80 {
		return false, "本店不接待80岁以上的老人哦～"
	}
	if len(tel) != 11 {
		return false, "请填写正确的手机号码"
	}
	cs.customerNum++
	customer := model.NewCustomer(cs.customerNum, name, gender, age, tel, email)
	cs.customers = append(cs.customers, customer)
	return true, ""
}

func (cs *CustomerService) Del(id int) (bool, string) {
	index := cs.FindById(id)
	if index == -1 {
		return false, "id不存在"
	}
	cs.customers = append(cs.customers[:index], cs.customers[index+1:]...)
	return true, ""
}

func (cs *CustomerService) Modify(id int, name string, gender string, age int, tel string, email string) (bool, string) {
	index := cs.FindById(id)
	if index == -1 {
		return false, "id不存在"
	}
	if gender != "男" && gender != "女" {
		return false, "请填写正确的性别"
	}
	if age < 18 {
		return false, "本店不接待未成年人哦～"
	} else if age > 80 {
		return false, "本店不接待80岁以上的老人哦～"
	}
	if len(tel) != 11 {
		return false, "请填写正确的手机号码"
	}
	cs.customers[index] = model.NewCustomer(id, name, gender, age, tel, email)
	return true, ""
}

func (cs *CustomerService) FindById(id int) int {
	for index, customer := range cs.customers {
		if customer.Id == id {
			return index
		}
	}
	return -1
}

func (cs *CustomerService) GetById(id int) (bool, model.Customer) {
	index := cs.FindById(id)
	if index == -1 {
		return false, model.Customer{
			Id:     -1,
			Name:   "",
			Gender: "",
			Age:    0,
			Tel:    "",
			Email:  "",
		}
	} else {
		return true, cs.customers[index]
	}

}

// List 展示明细
func (cs *CustomerService) List() []model.Customer {
	return cs.customers
}
